package com.atom.module.mvvm.base

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.ComponentCallbacks2
import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.os.Process
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.multidex.MultiDexApplication

abstract class AbstractApplication : MultiDexApplication() ,ViewModelStoreOwner {
    companion object {

        lateinit var applicationInstance: Application

        fun getInstance(): Application {
            return applicationInstance
        }
    }

    private val _viewModelStore by lazy { ViewModelStore() }

    override fun onCreate() {
        super.onCreate()
        applicationInstance = initApplication()
    }

    protected fun checkMain(block: () -> Unit) {
        // 多进程 会多次执行
        try {
            val am = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val runningApps = am.runningAppProcesses ?: return
            for (proInfo in runningApps) {
                if (proInfo.pid == Process.myPid() && proInfo.processName == this.packageName) {
                    block.invoke()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    protected open fun initApplication(): Application {
        return this
    }

    override fun getViewModelStore(): ViewModelStore {
        return _viewModelStore
    }
}